﻿namespace MA.MembershipProvider
{
    using System;
    using System.Collections.Specialized;
    using System.Configuration;
    using System.Text;
    using System.Web.Security;
    using System.Windows.Forms;
    using System.Xml;
    using System.Data.SqlClient;
    using System.Data;
    using System.Collections.Generic;

    public partial class frmDefault : Form
    {
        public frmDefault()
        {
            InitializeComponent();
        }

        private DataTable FillNameProvider()
        {
            string ContString = Properties.Settings.Default.ConnectionString;
            string strQuery = "SELECT ApplicationName FROM [aspnet_Applications]";

            DataTable oDataSet = new DataTable();

            using (SqlConnection con = new SqlConnection(ContString))
            {
                using (SqlDataAdapter adapter = new SqlDataAdapter(strQuery, con))
                {
                    using (new SqlCommandBuilder(adapter))
                    {
                        adapter.Fill(oDataSet);
                        con.Open();
                    }
                }
            }

            return oDataSet;
        }

        private void btoUsers_Click(object sender, EventArgs e)
        {
            try
            {
                if (comboBox1.Items.Count > 0)
                {
                    if (!string.IsNullOrWhiteSpace(comboBox1.Text))
                    {
                        Properties.Settings.Default.NombreAplicacion = comboBox1.Text;
                        Properties.Settings.Default.Save();

                        frmAdminUsers frm = new frmAdminUsers();
                        frm.Show();
                    }
                    else
                    {
                        MessageBox.Show("Por favor seleccione y/o ingrese el nombre de la aplicacion");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public string GetErrorMessage(MembershipCreateStatus status)
        {
            switch (status)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Username already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }

        private void btoSalir_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btoOpenDialog_Click(object sender, EventArgs e)
        {
            ofdWebConfig.DefaultExt = ".config";
            ofdWebConfig.Filter = "Web.config|*.config";
            ofdWebConfig.ShowDialog();
        }

        private void ofdWebConfig_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //txtDireccionWebConfig.Text = ofdWebConfig.FileName;
            //Properties.Settings.Default.WebConf = txtDireccionWebConfig.Text;
            //Properties.Settings.Default.Save();
        }

        public void updateConfigFile(string con)
        {
            //updating config file
            XmlDocument XmlDoc = new XmlDocument();
            //Loading the Config file
            XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
            foreach (XmlElement xElement in XmlDoc.DocumentElement)
            {
                if (xElement.Name == "connectionStrings")
                {
                    //setting the coonection string
                    xElement.FirstChild.Attributes[1].Value = con;
                }
            }
            //writing the connection string in config file
            XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        }

        private void frmDefault_Load(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = new DataTable();
                dt = FillNameProvider();

                string Nombr = Properties.Settings.Default.NombreAplicacion;

                foreach (DataRow item in dt.Rows)
                {
                    comboBox1.Items.Add(item[0].ToString());
                }

                comboBox1.Items.Add(Nombr);

                List<object> list = new List<object>();
                foreach (object o in comboBox1.Items)
                {
                    if (!list.Contains(o))
                    {
                        list.Add(o);
                    }
                }

                comboBox1.Items.Clear();
                comboBox1.Items.AddRange(list.ToArray());
            }
            catch (MembershipCreateUserException ex)
            {
                MessageBox.Show(GetErrorMessage(ex.StatusCode));
            }
            catch (Exception ex)
            {
                if (ex.Message == "Default Membership Provider must be specified.")
                {
                    MessageBox.Show(@"Por favor verifique que en su 'App.config' exista la sección  'membership/providers' y que contenga al menos un provider del type = 'SqlProvider' y que el name sea 'SqlProvider' ej:
                                      <membership userIsOnlineTimeWindow='15' defaultProvider='SqlProvider'>
                                            <providers>
                                              <clear />
                                                <add name='SqlProvider' 
                                                   type='System.Web.Security.SqlMembershipProvider'
                                                   connectionStringName='DefaultConnection' 
                                                   applicationName='MA De Santis' 
                                                   enablePasswordRetrieval='false' 
                                                   enablePasswordReset='true' 
                                                   requiresQuestionAndAnswer='false' 
                                                   requiresUniqueEmail='false' 
                                                   minRequiredPasswordLength='4' 
                                                   minRequiredNonalphanumericCharacters='0' 
                                                   passwordFormat='Hashed' />
                                            </providers>
                                          </membership> ");
                }
                else
                {
                    MessageBox.Show(ex.Message);
                }
                //Clipboard.SetText(ex.Message);
            }
        }

        private void frmDefault_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

    }
}
